package org.spiderflow.common.concurrent;

import org.apache.commons.lang3.RandomUtils;
import org.spiderflow.common.model.SpiderNode;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author zsh
 */
public class RandomThreadSubmitStrategy implements ThreadSubmitStrategy {

    private final List<SpiderFutureTask<?>> taskList = new CopyOnWriteArrayList<>();
    private static final Comparator<SpiderNode> COMPARATOR = (o1, o2) -> {
        if (Objects.equals(o1.getNodeId(), o2.getNodeId())) {
            return 0;
        } else {
            return RandomUtils.nextInt(0, 3) - 1;
        }
    };

    @Override
    public Comparator<SpiderNode> comparator() {
        return COMPARATOR;
    }

    @Override
    public void add(SpiderFutureTask<?> task) {
        taskList.add(task);
    }

    @Override
    public boolean isEmpty() {
        return taskList.isEmpty();
    }

    @Override
    public SpiderFutureTask<?> get() {
        return taskList.remove(RandomUtils.nextInt(0, taskList.size()));
    }
}
